<?php

namespace App\Admin\Controllers\Agent;

use App\Admin\Actions\Admin\OrderTend;
use App\Admin\Actions\Agent\Order\OrderStart;
use App\Admin\Actions\Agent\Order\OrderStop;
use App\Models\FlowChannel;
use App\Models\Order;
use App\Models\OrderReadInfo;
use App\Models\Setting as SettingModel;
use App\Models\Tire;
use Carbon\Carbon;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;

class OrderController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '订单';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Order());
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->equal('state', '订单状态')->select([
                Order::ORDER_STATE_AUDITING => '待审核',
                Order::ORDER_STATE_AUDIT_REFUSE => '拒绝',
                Order::ORDER_STATE_ON => '投放中',
                Order::ORDER_STATE_OFF => '关闭',
                Order::ORDER_STATE_COMPLETE => '完成',
                Order::ORDER_STATE_AUDIT_WAITING => '待投放',
            ]);

        });
        $grid->expandFilter();

        $grid->model()->where('admin_user_id', Auth::guard()->id())->orderByDesc('id');
        $grid->column('name', __('订单名称'))->modal('数据趋势', \App\Modals\OrderTend::class);
        $grid->column('type', __('订单类型'))->display(function ($item) {
            switch ($item) {
                case 0:
                    return '普通快单';
                    break;
                case 1:
                    return '曲线单';
                    break;

            }

        });
        $grid->column('url', __('url'))->width('250')->style('text-overflow: ellipsis;overflow: hidden;white-space: nowrap;height:35px;max-width: 250px;')->link()->copyable();
        $grid->column('expect_time', __('期望时间（小时）'))->style('text-align:center');
        $grid->column('cpm', __('千次展示收费（元）'))->style('text-align:center');
        $grid->column('speed_order', __('加速投放'))->display(function ($speed_order) {
            if ($speed_order) {
                return "<span style='color: green' >开启</span>";
            } else {
                return "<span style='color: red' >关闭</span>";
            }
        });
        $grid->column('tire.name', __('层级'));
        $grid->column('initialization_read_num', __('初始阅读数'))->style('text-align:center');
        $grid->column('current_read_num', __('当前阅读数'))->style('text-align:center');
        $grid->model()->collection(function (Collection $collection) {
            foreach ($collection as $item) {
                $item->expect_read = $item->expect_read_num - $item->initialization_read_num;//构造期望阅读
                if (($item->expect_read_num - $item->initialization_read_num) == 0) {
                    $item->com_rate = 0;
                } else {
                    $item->com_rate = round(($item->current_read_num - $item->initialization_read_num) / ($item->expect_read_num - $item->initialization_read_num), 2) * 100;//构造完成度
                }
                $item->amount = ($item->current_read_num - $item->initialization_read_num) * $item->cpm / 1000;
            }
            return $collection;
        });
        $grid->column('expect_read', __('期望阅读数'))->style('text-align:center');
        $grid->column('com_rate', __('完成度'))->display(function ($com_rate) {
            return $com_rate . '%';
        })->progress()->style('text-align:center');
        $grid->column('amount', __('消耗金额'))->style('text-align:center');
        $grid->column('state', __('状态'))->display(function ($state) {
            $text = '';
            switch ($state) {
                case Order::ORDER_STATE_AUDITING:
                    $text = "<span style='color: orange' >审核中</span>";
                    break;
                case Order::ORDER_STATE_AUDIT_REFUSE:
                    $text = "<span style='color: red' >拒绝</span>";
                    break;
                case Order::ORDER_STATE_ON:
                    $text = "<span style='color: green' >投放中</span>";
                    break;
                case Order::ORDER_STATE_OFF:
                    $text = '关闭';
                    break;
                case Order::ORDER_STATE_COMPLETE:
                    $text = '完成';
                    break;
                case Order::ORDER_STATE_AUDIT_WAITING:
                    $text = "<span style='color:blue' >待投放</span>";

                    break;
            }

            return $text;
        })->style('text-align:center');
        $grid->column('created_at', __('创建时间'));
        $grid->column('opened_at', __('开启时间'));
        $grid->column('stopped_at', __('结束时间'));

        $grid->actions(function ($action) use ($grid) {

            //待投放/进行中/审核中的订单无法编辑
            if (in_array($action->row->state, [Order::ORDER_STATE_AUDIT_WAITING, Order::ORDER_STATE_ON, Order::ORDER_STATE_AUDITING])) {
                $action->disableEdit();
            }
            //只有待投放订单可以开启
            if ($action->row->state == Order::ORDER_STATE_AUDIT_WAITING) {
                $action->add(new OrderStart());
            }
            //只有投放中订单可以关闭
            if ($action->row->state == Order::ORDER_STATE_ON) {
                $action->add(new OrderStop());
            }

            $action->disableView();
            $action->disableDelete();
        });

        $grid->disableBatchActions();


        return $grid;
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Order());
        $headers = ['订单类型', '时速'];
        $common_order_speed = OrderReadInfo::query()->where([
            'date' => Carbon::now()->toDateString(),
        ])->whereBetween('hour', [Carbon::now()->subHour()->hour, Carbon::now()->hour])
            ->whereHas('order', function ($order) {
                $order->where('type', Order::ORDER_TYPE_COMMON);
            })->selectRaw('sum(read_num_inc) as read_num_inc,count(distinct order_id) as order_num')
            ->first();
        $curve_order_speed = OrderReadInfo::query()->where([
            'date' => Carbon::now()->toDateString()
        ])->whereBetween('hour', [Carbon::now()->subHour()->hour, Carbon::now()->hour])
            ->whereHas('order', function ($order) {
                $order->where('type', Order::ORDER_TYPE_CURVE);
            })->selectRaw('sum(read_num_inc) as read_num_inc,count(distinct order_id) as order_num')
            ->first();
        $rows = [
            [
                '普通快单', intval($common_order_speed->read_num_inc / $common_order_speed->order_num)
            ],
            [
                '曲线单', $curve_order_speed->order_num == 0 ? 0 : intval($curve_order_speed->read_num_inc / $curve_order_speed->order_num)
            ]
        ];
        $table = new Table($headers, $rows);
        $form->html($table->render(), '时速参考');

        $bottom_price = json_decode(SettingModel::query()->firstOrCreate(['key' => 'bottom_price'], ['value' => null])->value);
        $speed_order_rate = json_decode(SettingModel::query()->firstOrCreate(['key' => 'speed_order_rate'], ['value' => null])->value);
        $form->text('name', __('订单名称'))->required();
        $form->url('url', __('url'))->required();
        $top_price = Order::query()->where('state', Order::ORDER_STATE_ON)->orderByDesc('cpm')->first()->cpm;
        $low_price = Order::query()->where('state', Order::ORDER_STATE_ON)->orderBy('cpm')->first()->cpm;
        $form->radioButton('type', __('订单类型'))->options([
            0 => '普通快单',
            1 => '曲线订单'

        ])->when(1, function (Form $form) {
            $form->number('expect_time', '期望完成时间（小时）')->min(1);
        })->required();
        $form->number('cpm', __('千次展示收费（元）'))->style('width', '150')
            ->rules(function ($form) use ($bottom_price, $speed_order_rate) {
                if (request()->speed_order == 'on') {
                    //加速订单，校验快单底价
                    $speed_order_price = $bottom_price * ($speed_order_rate / 100 + 1);
                    if (request()->cpm < $speed_order_price) {
                        return 'min:' . $speed_order_price;
                    }
                } else {
                    //普通订单，校验底价
                    if (request()->cpm < $bottom_price) {
                        return 'min:' . $bottom_price;
                    }
                }
                return 'min:0';
            }, [
                'min' => '出价不能低于底价'
            ])
            ->help("<span style='color:red'> 当前系统普通单底价：" . $bottom_price . "，系统订单最高价：" . $top_price . "；系统订单最低价：" . $low_price . "</span>");


        $form->number('expect_read_num', __('期望展示数'))->style('width', '150')->rules(['integer', 'min:100'])->placeholder('最小100单');
        $tires = Tire::query()->get()->pluck('name', 'id');
        $form->select('tire_id', __('层级选择'))->options($tires);


        $form->switch('speed_order', __('加速投放'))
            ->help("<span style='color:red'> 当前系统快单底价：" . $bottom_price * ($speed_order_rate / 100 + 1) . "</span>");
        $form->saving(function (Form $form) {
            $order = $form->model();
            $order->admin_user_id = Auth::guard()->id();
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableView();
            $tools->disableDelete();
        });

        return $form;
    }
}
